# 导入库
import pymysql
import pandas as pd
import pymysql.cursors

class MySQLutils(object):
    def __init__(self):
        self.conn = pymysql.connect(
            host='127.0.0.1',
            user='root',
            password='root',
            database='tushare',
            port=3306,
            charset='utf8'
        )

class ClassificationUtils(object):
    def __init__(self):
        pass

    def get_fina_indicator(self, conn):
        """
        获取财务数据
        """
        cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
        sql = """
        SELECT ts_code, ann_date, eps, total_revenue_ps, undist_profit_ps,
        gross_margin, fcff, fcfe, tangible_asset, bps, grossprofit_margin, npta
        FROM financial_data WHERE ann_date BETWEEN '2023-01-01' AND '2024-01-01'
        """
        cursor.execute(sql)
        rows = cursor.fetchall()
        df = pd.DataFrame(rows)
        # print(df.head())
        # 处理缺失数据
        df = df.dropna(subset=['eps', 'total_revenue_ps', 'undist_profit_ps', 'gross_margin', 'fcff', 'fcfe',
            'tangible_asset', 'bps', 'grossprofit_margin', 'npta'])
        # 重建索引
        df = df.reset_index(drop=True)
        return df

    def get_daily(self, conn, df):
        """
        获取回线数据
        """
        cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
        new_list = []
        for index, row in df.iterrows():
            print(index)
            ts_code = row['ts_code']
            ann_date = row['ann_date'].strftime('%Y-%m-%d')
            sql = f"""
            SELECT trade_date, closes FROM date_1 d WHERE d.trade_date > Date('{ann_date}') AND d.ts_code = '{ts_code}'
            ORDER BY d.trade_date ASC LIMIT 20
            """
            cursor.execute(sql) 
            rows = cursor.fetchall()
            df1 = pd.DataFrame(rows)
            try:
                if len(df1) > 0:
                    max_closes = df1["closes"].max() # 20天内最大收盘价
                    min_closes = df1["closes"].min() # 20天内最小收盘价
                    the_closes = df1["closes"].iloc[-1] # 20天内最新收盘价
                    new_list.append({
                        'ts_code': ts_code,
                        'ann_date': ann_date,
                        'max_closes': max_closes,
                        'min_closes': min_closes,
                        'the_closes': the_closes,
                        'eps': row['eps'],
                        'total_revenue_ps': row['total_revenue_ps'],
                        'undist_profit_ps': row['undist_profit_ps'],
                        'gross_margin': row['gross_margin'],
                        'fcff': row['fcff'],
                        'fcfe': row['fcfe'],
                        'tangible_asset': row['tangible_asset'],
                        'bps': row['bps'],
                        'grossprofit_margin': row['grossprofit_margin'],
                        'npta': row['npta'],
                    })
            except Exception as e:
                print(e)
                continue
        # 转换为DataFrame
        df2 = pd.DataFrame(new_list)
        df2.to_csv('fina_indicator.csv', index=False)
        
if __name__ == '__main__':
    mu = MySQLutils()
    classification_utils = ClassificationUtils()
    df = classification_utils.get_fina_indicator(mu.conn)
    classification_utils.get_daily(mu.conn, df)